// pages/foodform/foodform.js
var util = require('../../utils/util.js')
var config = require('../../config/config.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    array: config.foodStyles,
    objectArray: config.foodStylesObjectArray,
    index: 0,

    grids: [],
    shopId: 0,
    foodId: 0,
    foodName: '',
    showFoodNameTip: false,
    foodFlavor: '',
    foodPrice: '',
    showFoodPriceTip: false,
    foodImgSrc: './../../imgs/default_food.png',
    alreadyChooseFoodImage: false,
    foodDesc: '',
    showFoodDescTip: false,
    showAddFoodDesc: true,
    foodImgUrl: '',
    foodDescImgUrls: [],
    isEdit: false,
    latitude: 0,
    longitude: 0,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.setData({
      shopId: options.shop_id,
      foodId: options.food_id,
      latitude: options.latitude,
      longitude: options.longitude
    })

    let food_id = options.food_id
    let that = this

    wx.request({
      url: `${config.requestBaseUrl}/Dishes/getFoodInfo`,
      method: 'POST',
      data: {
        food_id: food_id,
        openid: wx.getStorageSync('openid')
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        // console.log(res)
        
        if (res.data.code === 1) {
          let imgGrids = []
          if (res.data.desc_img1 != "")
            imgGrids.push(res.data.desc_img1)
          if (res.data.desc_img2 != "")
            imgGrids.push(res.data.desc_img2)
          if (res.data.desc_img3 != "")
            imgGrids.push(res.data.desc_img3)
          let index = 0
          for (let i = 0, len = that.data.array.length; i < len; i++) {
            if (that.data.array[i] == res.data.food_style)
              index = i
          }
          // console.log(imgGrids)
          that.setData({
            grids: imgGrids,
            foodDescImgUrls: imgGrids,
            foodName: res.data.food_name,
            foodImgSrc: res.data.food_img,
            foodDesc: res.data.desc_text,
            foodFlavor: res.data.food_flavor,
            foodImgUrl: res.data.food_img,
            index: index,
            foodPrice: res.data.price,
            longitude: res.data.longitude,
            latitude: res.data.latitude,
            isEdit: true
          })
        } else {
          console.log("没有找到菜品信息")
        }
      }
    })



  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  bindPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },

  blurInputFoodName: function (e) {
    this.setData({
      foodName: e.detail.value
    })
    // console.log(this.data.foodName)
    if (this.data.foodName == '') {
      this.setData({
        showFoodNameTip: true
      })
    } else {
      this.setData({
        showFoodNameTip: false
      })
    }
  },

  blurInputFoodFlavor: function (e) {
    this.setData({
      foodFlavor: e.detail.value
    })
  },

  blurInputFoodPrice: function (e) {
    this.setData({
      foodPrice: e.detail.value
    })
    if (this.data.foodPrice == '') {
      this.setData({
        showFoodPriceTip: true
      })
    } else {
      this.setData({
        showFoodPriceTip: false
      })
    }
  },

  chooseFoodImg: function () {
    let that = this
    util.chooseImage(function(res) {
      that.setData({
        foodImgSrc: res.tempFilePaths[0],
        alreadyChooseFoodImage: true
      })
    })
  },

  blurInputFoodDesc: function (e) {
    this.setData({
      foodDesc: e.detail.value
    })
    if (this.data.foodDesc == '') {
      this.setData({
        showFoodDescTip: true
      })
    } else {
      this.setData({
        showFoodDescTip: false
      })
    }
  },

  chooseFoodDescImg: function() {
    let that = this
    let imgGrids = this.data.grids
    if (imgGrids.length >= 3) {
      return
    }
    util.chooseImage(function (res) {
      let needImgNum = 3 - imgGrids.length
      let imgNum = needImgNum >= res.tempFilePaths.length ? res.tempFilePaths.length : needImgNum
      for (let i = 0; i < imgNum; i++) {
        imgGrids.push(res.tempFilePaths[i])
      }
      that.setData({
        grids: imgGrids
      })
      if (that.data.grids.length >= 3) {
        that.setData({
          showAddFoodDesc: false
        })
      }
    })
  },

  clickDeleteDescImg: function(event) {
    let index = event.currentTarget.dataset.index
    let imgGrids = this.data.grids
    let imgUrls = this.data.foodDescImgUrls
    imgGrids.splice(index, 1)
    if (this.data.isEdit) {
      imgUrls.splice(index, 1)
    }
    this.setData({
      grids: imgGrids,
      foodDescImgUrls: imgUrls
    })
    if (this.data.grids.length < 3) {
      this.setData({
        showAddFoodDesc: true
      })
    }
  },


  clickUploadFoodInfo: function() {
    if (this.data.foodName == '') {
      this.showTipModal("请输入菜品名称")
      return
    }
    if (this.data.foodPrice == '') {
      this.showTipModal("请输入菜品价格")
      return
    }
    if (!this.data.alreadyChooseFoodImage && !this.data.isEdit) {
      this.showTipModal("请上传菜品图片")
      return
    }
    if (this.data.foodDesc == '') {
      this.showTipModal("请输入菜品描述")
      return
    }
    wx.showLoading({
      title: '上传中...',
    })

    if (this.data.foodImgSrc == this.data.foodImgUrl) {
      this.uploadFoodDescImgs()
    } else {
      this.uploadFoodImg()
    }
    
  },

  uploadFoodImg: function () {
    let that = this
    util.wxUploadFile(this.data.foodImgSrc,
      successRes => {
        that.setData({
          foodImgUrl: successRes.fileUrl
        })
        that.uploadFoodDescImgs()
      },
      failRes => {
        wx.hideLoading()
        // console.log(failRes)
      }
    )
  },

  uploadFoodDescImgs: function () {
    let that = this
    let imgGrids = this.data.grids
    let imgUrls = this.data.foodDescImgUrls
    let urlGrids = []
    // console.log(imgGrids)
    for (let i=0, len=imgGrids.length; i<len; i++ ) {
      if (imgGrids[i] == imgUrls[i]) {
        urlGrids.push(imgUrls[i])
        if (urlGrids.length == len) {
          that.setData({
            foodDescImgUrls: urlGrids
          })
          that.uploadFoodInfoToServer()
        }
        continue
      }
      util.wxUploadFile(imgGrids[i],
        successRes => {
          urlGrids.push(successRes.fileUrl)
          if (urlGrids.length == len) {
            that.setData({
              foodDescImgUrls: urlGrids
            })
            that.uploadFoodInfoToServer()
          }
        },
        failRes => {
          console.log(failRes)
        }
      )
    }
    if (imgGrids.length == 0) {
      that.uploadFoodInfoToServer()
      wx.hideLoading()
    }
  },

  uploadFoodInfoToServer: function() {
    // console.log(this.data)
    // return
    let that = this
    wx.request({
      url: `${config.requestBaseUrl}/Dishes/uploadDishesInfo`,
      method: 'POST',
      data: {
        food_id: this.data.foodId,
        openid: wx.getStorageSync('openid'),
        food_name: this.data.foodName,
        shop_id: this.data.shopId,
        food_img: this.data.foodImgUrl,
        desc_text: this.data.foodDesc,
        desc_img1: typeof (this.data.foodDescImgUrls[0]) == 'undefined' ? '' : this.data.foodDescImgUrls[0],
        desc_img2: typeof (this.data.foodDescImgUrls[1]) == 'undefined' ? '' : this.data.foodDescImgUrls[1],
        desc_img3: typeof (this.data.foodDescImgUrls[2]) == 'undefined' ? '' : this.data.foodDescImgUrls[2],
        price: this.data.foodPrice,
        food_style: this.data.array[this.data.index],
        food_flavor: this.data.foodFlavor,
        longitude: this.data.longitude,
        latitude: this.data.latitude
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success(res) {
        wx.hideLoading()
        if (res.data.code == 1) {
          let food_id = res.data.food_id
          wx.showToast({
            title: '已完成',
            duration: 1500,
            success: function () {
              wx.redirectTo({
                url: `../food/food?food_id=${food_id}`,
              })
            }
          })
        } else {
          that.showTipModal('上传错误')
          console.log(res.data)
        }
      }
    })
  },

  showTipModal: function (tipInfo) {
    wx.showModal({
      content: tipInfo,
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          // console.log('用户点击确定')
        }
      }
    });
  },




})